import applicationApi from '@/api/application';
import { datetimeFormat } from '@/utils/time';
import { CopyOutlined, DislikeOutlined, LikeOutlined, PauseCircleOutlined, PlayCircleOutlined, RedoOutlined } from '@ant-design/icons';
import { Button, Divider, message, Tooltip, Typography } from 'antd';
import { useMemo, useRef, useState } from 'react';
import { useParams } from 'react-router-dom';
import { markdownToPlainText, removeFormRander } from './util';
const { Text } = Typography;

interface ChatOperationButtonProps {
  data: any
  type: 'log' | 'ai-chat' | 'debug-ai-chat'
  chatId: string
  chat_loading: boolean
  applicationId: string
  tts: boolean
  tts_type: string,
  onChangeData?: (data: any) => void;
  onRegeneration?: () => void
}

const ChatOperationButton = (props: ChatOperationButtonProps) => {
  const {
    data = {},
    type = 'ai-chat',
    chatId,
    chat_loading,
    applicationId,
    tts,
    tts_type,
    onChangeData,
    onRegeneration
  } = props;

  const { id } = useParams();


  const [audioPlayerStatus, setAudioPlayerStatus] = useState(false)

  const [buttonData, setButtonData] = useState(data);
  const [utterance, setUtterance] = useState<SpeechSynthesisUtterance | null>(null)
  const [loading, setLoading] = useState(false);

  const audioPlayer = useRef<HTMLAudioElement>(null);

  const titleNode = useMemo(() => {
    return <Text>
      { datetimeFormat(data.create_time) }
    </Text>
  }, [data.create_time])

  const voteHandle = (val: string) => {
    applicationApi
    .putChatVote(applicationId, chatId, data.record_id, val, loading)
    .then(() => {
      setButtonData((data: any) => ({...data, vote_status: val}))
      onChangeData && onChangeData(buttonData)
    })
  }
  
  const playAnswerText = (text: string) => {
    if (!text) {
      text = '抱歉，没有查找到相关内容，请重新描述您的问题或提供更多信息。'
    }
    // 移除表单渲染器
    text = removeFormRander(text)
    // text 处理成纯文本
    text = markdownToPlainText(text)
    // console.log(text)
    setAudioPlayerStatus(true)
    if (props.tts_type === 'BROWSER') {
      if (text !== utterance?.text) {
        window.speechSynthesis.cancel()
      }
      if (window.speechSynthesis.paused) {
        window.speechSynthesis.resume()
        return
      }
      // 创建一个新的 SpeechSynthesisUtterance 实例
      const newUtterance = new SpeechSynthesisUtterance(text);
      newUtterance.onend = () => {
          setAudioPlayerStatus(false);
          setUtterance(null);
      };
      newUtterance.onerror = () => {
          setAudioPlayerStatus(false);
          setUtterance(null);
      };

      setUtterance(newUtterance);
      // 调用浏览器的朗读功能
      window.speechSynthesis.speak(newUtterance)
      
    }
    if (props.tts_type === 'TTS') {
      // 恢复上次暂停的播放
      if (audioPlayer.current?.src) {
        audioPlayer.current?.play()
        return
      }
      applicationApi
        .postTextToSpeech((props.applicationId as string) || (id as string), { text: text }, loading)
        .then(async (res: any) => {
          if (res.type === 'application/json') {
            const text = await res.text()
            message.error(text)
            return
          }
          // 假设我们有一个 MP3 文件的字节数组
          // 创建 Blob 对象
          const blob = new Blob([res], { type: 'audio/mp3' })
  
          // 创建对象 URL
          const url = URL.createObjectURL(blob)
  
          // 测试blob是否能正常播放
          // const link = document.createElement('a')
          // link.href = window.URL.createObjectURL(blob)
          // link.download = "abc.mp3"
          // link.click()
  
          // 检查 audioPlayer 是否已经引用了 DOM 元素
          if (audioPlayer.current instanceof HTMLAudioElement) {
            audioPlayer.current.src = url
            audioPlayer.current.play() // 自动播放音频
            audioPlayer.current.onended = () => {
              setAudioPlayerStatus(false)
            }
          } else {
            console.error('audioPlayer.value is not an instance of HTMLAudioElement')
          }
        })
        .catch((err) => {
          console.log('err: ', err)
        })
    }
  }

  // useEffect(() => {
  //   if (utterance) {
  //     // 调用浏览器的朗读功能
  //     window.speechSynthesis.speak(utterance)
  //   }
    
  // }, [utterance])

  const pausePlayAnswerText = () => {
    setAudioPlayerStatus(false)
    if (props.tts_type === 'TTS') {
      audioPlayer?.current?.pause()
    }
    if (props.tts_type === 'BROWSER') {
      window.speechSynthesis.pause()
    }
  }

  const copyClick = (text: string) => {
    navigator.clipboard.writeText(text).then(() => {
      // 显示复制成功的提示
      message.success('复制成功！');
    }).catch((error) => {
      console.error(error)
      message.error('复制失败：');
    });
  }

  const handleRegeneration = () => {
    onRegeneration && onRegeneration()
  }

  return (
    <>
    <div>
      {titleNode}
    </div>
    <div>
      {/* 语音播放 */}
      {tts && (
        <>
          {!audioPlayerStatus ? (
            <Tooltip title="点击播放" placement="top">
              <Button type="text" disabled={!data?.write_ed} onClick={() => playAnswerText(data?.answer_text)}>
                <PlayCircleOutlined />
              </Button>
            </Tooltip>
          ) : (
            <Tooltip title="停止" placement="top">
              <Button type="primary" disabled={!data?.write_ed} onClick={pausePlayAnswerText}>
                <PauseCircleOutlined />
              </Button>
            </Tooltip>
          )}
          <Divider type="vertical" />
        </>
      )}
      {(type === 'ai-chat' || type === 'log') && (
        <>
          <Tooltip title="换个答案" placement="top">
            <Button type="text" disabled={chat_loading} onClick={handleRegeneration}>
              <RedoOutlined />
            </Button>
          </Tooltip>
          <Divider type="vertical" />
          <Tooltip title="复制" placement="top">
            <Button type="text" onClick={() => copyClick(data?.answer_text)}>
              <CopyOutlined />
            </Button>
          </Tooltip>
          <Divider type="vertical" />
          {buttonData?.vote_status === '-1' && (
            <>
              <Tooltip title="赞同" placement="top">
                <Button type="text" disabled={loading} onClick={() => voteHandle('0')}>
                  <LikeOutlined />
                </Button>
              </Tooltip>
              <Divider type="vertical" />
              <Tooltip title="反对" placement="top">
                <Button type="text" disabled={loading} onClick={() => voteHandle('1')}>
                  <DislikeOutlined />
                </Button>
              </Tooltip>
            </>
          )}
          {buttonData?.vote_status === '0' && (
            <Tooltip title="取消赞同" placement="top">
              <Button type="text" disabled={loading} onClick={() => voteHandle('-1')}>
                <LikeOutlined twoToneColor="rgb(255, 198, 10)"/>
              </Button>
            </Tooltip>
          )}
          {buttonData?.vote_status === '1' && (
            <Tooltip title="取消反对" placement="top">
              <Button type="text" disabled={loading} onClick={() => voteHandle('-1')}>
                <DislikeOutlined twoToneColor="rgb(255, 198, 10)"/>
              </Button>
            </Tooltip>
          )}
        </>
      )}
    </div>
    {/* 先渲染，不然不能播放 */}
    <audio ref={audioPlayer} controls hidden={true} ></audio>
    </>
  )
}


export default ChatOperationButton;